<?php 
	require("php2/functions.php"); 
	require("php2/conexao.php");
	$time = getdate();
	$data_atual = "$time[year]/$time[mon]/$time[mday]";
	$fim_mes = "$time[year]/$time[mon]/30";
?>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript" src="js/javascript.js"></script>
<!--<link href="resources/css/default.css" rel="stylesheet" type="text/css"/>-->
<link href="resources/css/jquery.click-calendario-1.0.css" rel="stylesheet" type="text/css"/> 
<link type="text/css" href="resources/css/jquery-ui-1.8.16.custom.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.click-calendario-1.0-min.js"></script>		
<script type="text/javascript" src="js/exemplo-calendario.js"></script>
<script type="text/javascript" src="js/jquery-ui.min.js"></script>
<!-- DIALOG -->
<script src="js/plugins/dialog/jquery.ui.core.js"></script>
<script src="js/plugins/dialog/jquery.ui.widget.js"></script>
<script src="js/plugins/dialog/jquery.ui.mouse.js"></script>
<script src="js/plugins/dialog/jquery.ui.button.js"></script>
<script src="js/plugins/dialog/jquery.ui.draggable.js"></script>
<script src="js/plugins/dialog/jquery.ui.position.js"></script>
<script src="js/plugins/dialog/jquery.ui.resizable.js"></script>
<script src="js/plugins/dialog/jquery.ui.dialog.js"></script>
<script src="js/plugins/dialog/jquery.effects.core.js"></script>
<!-- DIALOG -->	
<!-- Uploadify -->
<link href="uploadify/uploadify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="uploadify/swfobject.js"></script>
<script type="text/javascript" src="uploadify/jquery.uploadify.v2.1.4.min.js"></script>
<!-- Uploadify -->
<!-- DataTables -->
<script src="js/jquery.DataTables.min.js" type="text/javascript"></script>
<script src="js/jquery.jeditable.js" type="text/javascript"></script>
<script src="js/jquery.jpaging.js" type="text/javascript"></script>
<script src="js/jquery-ui.js" type="text/javascript"></script>
<script src="js/jquery.validate.js" type="text/javascript"></script>
<script src="js/jquery.DataTables.editable.js" type="text/javascript"></script>
<!-- DataTables -->
<style type="text/css">
<!--
.style1 {color: #333333}
-->
</style>

<script type="text/javascript">
var Selected = "";
var counter = 0;
var pos;

$(document).ready(function(){
 $(function() {
	  $("#file_upload").uploadify({
      'uploader'    : 'uploadify/uploadify.swf',
      'script'      : 'uploadify/uploadify.php',
      'cancelImg'   : 'uploadify/cancel.png',
      'folder'      : 'ofx/',
      'multi'       : false,	  
	  'buttonText'  : 'Buscar',
      'onComplete'  : function(event, ID, fileObj, response, data) {          
		  if (response.match("existe") == 'existe' || response.match("inválido") == "inválido"){
			 alert(response);
		  }
		  else {
			 $.ajax({
			 url: "php2/Insert.php", 
			 data: {data: response}, 
			 type: "POST", 
			 success: function(result){
				//$("#tabela2").html(result);
				document.getElementById('tabela2').innerHTML = result;
				var tabela = document.getElementById('tbextrato');
				document.getElementById('total').value = contV(tabela);
				$('#tbextrato').dataTable().makeEditable({
						sAddURL: 'php2/AddData.php',
						sUpdateURL: 'php2/UpdateData.php',
                    	sDeleteURL: 'php2/DeleteData.php'
					});	
				
			 }});
		  }
		  $('#file_upload').uploadifyClearQueue();
		  $('#upload').dialog('close');
        }
    });

	$("#upload").dialog({
		autoOpen: false,
		heigth: 250,
		width: 400,
		modal: true,
		title: "Enviar arquivo",		
		buttons: {
			"Enviar" : function() {
				$('#file_upload').uploadifyUpload();				
			}
		}
	});
	
	$("#confirma").dialog({
		autoOpen: false,
		heigth: 250,
		width: 400,
		modal: true,
		title: "Finalizar operação?"
	});
	
	/*$("#dvagenda").dialog({
		autoOpen: false,
		heigth: 600,
		width: 600,
		modal: false,
		title: "Agenda"
	});*/
	
	$("#cadconta").dialog({
		autoOpen: false,
		heigth: 150,
		width: 300,
		modal: true,
		title: "Erro",
		buttons: {
			"OK" : function(){
				$(this).dialog('close');
			},
			"Ir para Cadastrar Conta" : function(){
				$(this).dialog('close');
				location = "index2.php?link=12";
			}
		}
	});
	
	$("#btnAgenda").click(function(){
		//$('#dvagenda').dialog('open');
		if (counter % 2 == 0){
			$("#dvagenda").show();
		}else{
			$("#dvagenda").hide();
		}
		counter++;
	});
	
	$("#btnFechar").click(function(){
		//$('#dvagenda').dialog('close');
		$("#dvagenda").hide();
	});
	
	$("#import").click(function(){
		$('#upload').dialog('open');
	});
	
	$("#btncancelar").click(function(){
		$('#confirma').dialog('open');
	});
	$("#nao").click(function(){
		$('#confirma').dialog('close');
	});
	
	$('#teste').dialog({
		autoOpen: false,
		heigth: 250,
		width: 400,
		modal: true,
		title: "TESTE",		
		buttons: {
			"OK" : function() {
				$(this).dialog('close');
			}
		}
	});
	//Método em teste
	$("#concluir").click(function(){
		if (document.getElementById('tbextrato') != null){
		var tabela = document.getElementById('tbextrato');
		var dados = new Array();
		
		for (i=1; i < tabela.rows.length; i++){			
			id = tabela.rows[i].id;
			colunas = tabela.rows[i].cells;
			dados[(i-1)]= new Array(id, colunas[2].innerHTML);
		}
		$.ajax({
		url: "php2/concluir.php", 
		data: {data: dados}, 
		type: "POST", 
		success: function(result){			
			if (result){						
			location = "index2.php?link=1";
			}else {
			alert(result);
			}
		}});
		}else {
			alert("Nenhum dado para inserir");
		}		
	});
	
	$("#cancelar").click(function(){
		if (document.getElementById('tbextrato') != null){
		var tabela = document.getElementById('tbextrato');
		var dados = new Array();
		
		for (i=1; i < tabela.rows.length; i++){			
			id = tabela.rows[i].id;
			colunas = tabela.rows[i].cells;
			dados[(i-1)]= new Array(id, colunas[2].innerHTML);
		}
		$.ajax({
		url: "php2/cancelar.php", 
		data: {data: dados}, 
		type: "POST", 
		success: function(result){			
			if (result){						
			location = "index2.php?link=1";
			}else {
			alert(result);
			}
		}});
		}else {
			location = "index2.php?link=1";
		}		
	});
	
	$("#tbcontas tbody tr").click( function () {
        		                   
        Selected = TableA.fnGetData( this );         
        pos = TableA.fnGetPosition( this ) ;
    });
	
	$("#btnImport").click(function (){
		if (Selected != "")
		{
			TableE.fnAddData([Selected[0], 0, Selected[2], Selected[3]]);
			Selected = "";
			TableA.fnDeleteRow(pos);
			pos = "";
		}
		else
		{
			alert("Selecione uma linha para transferir");
		}
	});
	
	
	TableE = $("#tbextrato").dataTable({
        "oLanguage": {
            "sLengthMenu": "Mostrar _MENU_ linhas por página",
            "sZeroRecords": "Nenhum dado encontrado",
            "sInfo": "Mostrando _START_ a _END_ de _TOTAL_ linhas",
            "sInfoEmpty": "Mostrando 0 a 0 de 0 linhas",
            "sInfoFiltered": "( de um total de _MAX_ linhas)",
			"sEmptyTable": "Nenhum dado a ser mostrado",
			"sSearch": "Buscar:"
        }
		}).makeEditable({
						sAddURL: "php2/AddData.php",
						sUpdateURL: "php2/UpdateData.php",
                    	sDeleteURL: "php2/DeleteData.php",
						oAddNewRowOkButtonOptions: {
								label: 'Adicionar',
                                icons: { primary: 'ui-icon-check' },
                                name: 'action',
                                value: 'add-new'
                            },
                            oAddNewRowCancelButtonOptions: { 
								label: 'Fechar',
                                class: 'back-class',
                                name: 'action',
                                value: 'cancel-add',
                                icons: { primary: 'ui-icon-close' }
                            },
                            oAddNewRowFormOptions: {
								title: 'Cadastrar Extrato',
                                show: 'blind',
                                hide: 'explode'
                            },
							fnOnDeleting: function(tr)
							{ 																	
								
								return true;
							}/*,
							fnOnDeleted: function()
							{ 	
								contaV();
							},
							fnOnAdded: function()
							{ 	
								contaV();
							}*/
					});	
					
		TableA = $("#tbcontas").dataTable({
			"oLanguage": {
            "sLengthMenu": "Mostrar _MENU_ linhas por página",
            "sZeroRecords": "Nenhum dado encontrado",
            "sInfo": "Mostrando _START_ a _END_ de _TOTAL_ linhas",
            "sInfoEmpty": "Mostrando 0 a 0 de 0 linhas",
            "sInfoFiltered": "( de um total de _MAX_ linhas)",
			"sEmptyTable": "Nenhum dado a ser mostrado",
			"sSearch": "Buscar:"
			}
		})
 });
 
 $("#dvagenda").hide();
	
});
</script>
<script>
function contaV(){
	var valor = 0;
	if (document.getElementById('tbextrato') != null){
		var table = document.getElementById('tbextrato'); 
		
	
		for (i=1; i < tabela.rows.length; i++){						
			colunas = tabela.rows[i].cells;
			valor = valor + parseFloat(colunas[3].innerHTML);
		}
		document.getElementById('total').value = valor;
	}
}
</script>
</head>

<body>
<form id="formAddNewRow" action="#" title="Inserir novo extrato manualmente">
	<label for="name">Data:</label><input type="text" name="data_tr" id="data_tr" class="required" rel="0" />
	<br />
	<label for="name">NºDoc</label><input type="text" name="ndoc" id="ndoc" class="required" rel="1" />
	<br />
	<label for="name">Descrição</label><input type="text" name="desc" id="desc" class="required" rel="2" />
	<br />
	<label for="name">Valor</label><input type="text" name="valor" id="valor" class="required" rel="3" />
	<br />	
	<input type="reset" value="Limpar Campos" />
</form>

<div id="cadconta" class="ui-widget ui-widget-content">
<p>A conta encontrada no arquivo não está cadastrada. Por favor cadastre a nova conta, ou importe arquivos de contas já cadastradas.</p>

</div>

<div id="confirma" class="ui-widget ui-widget-content">
<p>Deseja realmente sair e excluir todo o conteudo adicionado até agora?</p>
<button id="cancelar">Sim</button>
<button id="nao">Não</button>
</div>

<div id="upload" class="ui-widget">
	  <form>	  
		<p>Selecione um arquivo que tenha seu extrato(formato ofx)<br />
		<input type="file" name="file_upload" id="file_upload" accept="file/ofx|ofc" /></p>
	  </form>
</div>


<div class="global-div" class="ui-widget">

<ul class="abas">
    <li><a href="#noticia1">Adicionar/Alterar Extrato</a></li>
</ul>

<div id="noticia"></div>

<div id="conteudo">

    <div id="noticia1" >

    <!--<p>Data: 
      <input type="text" name="data_1" id="data_1" size="10" maxlength="10" class="text ui-widget-content ui-corner-all"/>
	</p>-->    
	
    <div id="tabela2" class="ui-widget ui-widget-content">
	<?php 
	if (check()){
		echo "<script>alert('Sobraram dados da última utilização. Por favor termine de editá-los.')</script>";
		cTabelaE("", "", "1"); 		
	}else{
		$inf = date("Y-m-d", mktime(0,0,0,date("m"),date("d"),date("Y")+100));
		cTabelaE($inf, $inf, "");
	}
	?>
	<p>
      <button type="button" id="btnAddNewRow" >Novo</button>
	  <button type="button" id="btnDeleteRow" >Deletar</button>
	  <button type="button" id="import" >Importar Extrato</button>
	  <button type="button" id="btnAgenda" >Agenda</button>
    </p>
    </div>
    <div id="dvagenda" class="ui-widget ui-widget-content">
	<?php
		cTabelaA($data_atual, $fim_mes);
	?>
	<button id="btnImport">Enviar para extrato</button>
	<button id="btnFechar">Fechar</button>
	
		</div>
    <p>
	<!--Total:      
    <input type="text" name="textfield" id="total" value="0,00" class="text ui-widget-content ui-corner-all" />
    Restante:
    <input type="text" name="textfield2" id="restante" value="0,00" class="text ui-widget-content ui-corner-all" />-->
    </p>     
    
    <p>Observações:</p>
    <p>
      <label>
      <textarea name="textarea" id="obs" cols="45" rows="5"></textarea>
      </label>
    </p>
    <p>
      <label>
      <button type="button" id="concluir" >Concluir</button>
      </label>
      <label>
      <button type="button"  id="btncancelar" >Cancelar</button>
      </label>
    </p>
    </div>
	

    </div> 
	
</div>

</body>
</html>